package com.ruitaowang.admin.view.admin;

import com.alibaba.fastjson.JSON;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.RoleService;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.Role;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.properties.ConfigProperties;
import com.ruitaowang.core.utils.ImageUtils;
import com.ruitaowang.core.utils.QRCode;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.dao.Base64ImgMapper;
import com.ruitaowang.goods.service.UserMembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import wx.wechat.common.Configure;

import java.util.List;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class PageUserController extends BaseController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private Base64ImgMapper base64ImgMapper;
    @Autowired
    private UserMembersService userMembersService;

    private void init() {
        //init
        Configure.hostAPI = configProperties.getHostAPI();
        Configure.hostOSS = configProperties.getHostOSS();
        Configure.hostWap = configProperties.getHostWap();
        Configure.returnUri = configProperties.getReturnUri();
        Configure.wxpay_notify_url = configProperties.getHostAPI() + "/api/wxs/notify";;
    }

    /**
     * 资源 － 更新资源
     */
    @RequestMapping(value = {"/user_role_update/{userId}"}, method = RequestMethod.GET)
    public ModelAndView updateUserRolePage(Model model, @PathVariable("userId") Long userId) {
        if (ObjectUtils.isEmpty(LYSecurityUtil.currentSysUser())) {
            return new ModelAndView("/web/login");
        }

        SysUser user = userService.selectByPK(userId);
        List<Role> hasRoles = roleService.selectBatch(userId);
        List<Role> allRoles = roleService.select(new Role());
        LOGGER.error(JSON.toJSONString(allRoles));
        LOGGER.error(JSON.toJSONString(hasRoles));
        if(!ObjectUtils.isEmpty(hasRoles)){
            for (Role role : allRoles) {
                boolean flag = false;
                for (Role role1 : hasRoles) {
                    if(role.getId() == role1.getId()){
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    role.setRstatus((byte) 1);
                }
            }
        }
        LOGGER.error(JSON.toJSONString(allRoles));
        LOGGER.error(JSON.toJSONString(hasRoles));
        model.addAttribute("user", user);
        model.addAttribute("allroles", allRoles);
        return new ModelAndView("/web/user_role_update");
    }

    @RequestMapping(value = {"/user_member_update/{userId}"}, method = RequestMethod.GET)
    public ModelAndView updateUsermemberPage(Model model, @PathVariable("userId") Long userId) {
        if (ObjectUtils.isEmpty(LYSecurityUtil.currentSysUser())) {
            return new ModelAndView("/web/login");
        }

        SysUser user = userService.selectByPK(userId);
        List<Role> hasRoles = roleService.selectBatch(userId);
        List<Role> allRoles = roleService.select(new Role());
        LOGGER.error(JSON.toJSONString(allRoles));
        LOGGER.error(JSON.toJSONString(hasRoles));
        if(!ObjectUtils.isEmpty(hasRoles)){
            for (Role role : allRoles) {
                boolean flag = false;
                for (Role role1 : hasRoles) {
                    if(role.getId() == role1.getId()){
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    role.setRstatus((byte) 1);
                }
            }
        }
        LOGGER.error(JSON.toJSONString(allRoles));
        LOGGER.error(JSON.toJSONString(hasRoles));
        model.addAttribute("user", user);
        model.addAttribute("allroles", allRoles);
        return new ModelAndView("/web/user_member_update");
    }

    /**
     *  角色 － 更新角色
     */
    @RequestMapping(value = {"/user_role_grant"}, method = RequestMethod.POST)
    public String updateUserRole(Long userId, String roleIds) {
        if (ObjectUtils.isEmpty(LYSecurityUtil.currentSysUser())) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        roleService.grantUserRole(userId, roleIds);
        return this.renderJson(MsgOut.success());
    }

    /**
     * 图片base64 for myqr
     */
    @RequestMapping(value = {"/base64"})
    public String base64(String url) {
//        if (ObjectUtils.isEmpty(LYSecurityUtil.currentSysUser())) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
        return this.renderText("data:image/jpeg;base64,"+ImageUtils.imageToBase64FromRemote(url));
    }

    @RequestMapping(value = {"/base64/{imageId}"})
    public String base64(@PathVariable Long imageId) {
//        if (ObjectUtils.isEmpty(LYSecurityUtil.currentSysUser())) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
        return this.renderJson(MsgOut.success(base64ImgMapper.selectByPK(imageId)));
    }

    /**
     * check online
     */
    @RequestMapping(value = {"/online"})
    public String online() {
        if (ObjectUtils.isEmpty(LYSecurityUtil.currentSysUser())) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        return this.renderJson(MsgOut.success());
    }

    /**
     * PC端 商家入驻
     */
    @RequestMapping(value = {"/qr/pc/bizJoin"})
    public String bizJoinForPC() {
        init();
        if("www.ruitaowang.com".indexOf(Configure.hostWap)>-1){
            return this.renderText("http://static.ruitaowang.com/qr/qr_biz_join.png");
        }
        return this.renderText("http://static.ruitaowang.com/qr/qr_biz_join_test.png");
    }
    /**
     * PC端 加盟合作
     */
    @RequestMapping(value = {"/qr/pc/bizCo"})
    public String bizCoForPC() {
        init();
        if("www.ruitaowang.com".indexOf(Configure.hostWap)>-1){
            return this.renderText("http://static.ruitaowang.com/qr/qr_biz_co.png");
        }
        return this.renderText("http://static.ruitaowang.com/qr/qr_biz_co_test.png");
    }
    /**
     * PC端 扫码注册
     */
    @RequestMapping(value = {"/qr/pc/register"})
    public String registerForPC() {
        init();
        if("www.ruitaowang.com".indexOf(Configure.hostWap)>-1){
            return this.renderText("http://static.ruitaowang.com/qr/qr_register.png");
        }
        return this.renderText("http://static.ruitaowang.com/qr/qr_register_test.png");
    }

    /**
     * PC端 购买 -> 商品详情
     */
    @RequestMapping(value = {"/qr/pc/goodsDetail"})
    public String goodsDetailForPC(Long goodsId) {
        init();
        return this.renderText(QRCode.rulesQRForPCGoodsDetail(System.getProperty("catalina.base"), goodsId));
    }
}